import axios from 'axios'
import store from '@/store'
import errorCode from '@/utils/errorCode'
import { Message, MessageBox, Notification } from 'element-ui'
import { getPath } from '@/utils/common'
import { getAccessToken, getRefreshToken, setToken } from '@/utils/auth'

//是否显示重新登录
export let isReLogin = { show: false }

//请求队列
let requestList = []

// 是否正在刷新中
let isRefreshToken = false

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

//创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API + '', //axios中请求配置有baseURL选项，表示请求URL公共部分
  timeut: 30000,
  withCredentials: false, //禁用cookie信息
})

//request拦截器
service.interceptors.request.use(
  (config) => {
    //是否需要配置token
    const isToken = (config.headers || {}).isToken === false
    if (getAccessToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer' + getAccessToken() //让每个请求携带自定义token
    }
    //get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        const part = encodeURIComponent(propName) + '='
        if (value !== null && value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              let params = propName + '[' + key + ']'
              const subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
)

//响应拦截器
service.interceptors.response.use(
  async (res) => {
    //未设置状态码则默认成功状态
    const code = res.data.code || 200
    //获取错误信息
    const msg = res.data.msg || errorCode[code] || errorCode['default']
    //如果是忽略的错误码，直接返回msg异常
    if (ignoreMsgs.indexOf(msg) !== -1) {
      return Promise.reject(msg)
    } else if (code === 401) {
      //如果未认证，并刷新令牌，说明可能是访问令牌过期了
      if (!isRefreshToken) {
        isRefreshToken = true
        //如果获取不到刷新令牌，则只能执行登出操作
        if (!getRefreshToken()) {
          return handleAuthorized()
        }
        //进行刷新访问令牌
        try {
          const refreshTokenRes = await refreshToken()
          //刷新成功，则放回队列的请求 + 当前请求
          setToken(refreshTokenRes.data)
          requestList.forEach((cb) => cb())
          return service(res.config)
        } catch (e) {
          //刷新失败，请求因为Promise.reject触发异常
          //刷新失败，只放回队列的请求
          requestList.forEach((cb) => cb())
          //提示是否要登出，即不放回当前请求不会形成递归
          return handleAuthorized()
        } finally {
          requestList = []
          isRefreshToken = false
        }
      } else {
        //添加到队列，等待刷新获取到新的令牌
        return new Promise((resolve) => {
          requestList.push(() => {
            res.config.headers['Authorization'] = 'Bearer' + getAccessToken() //让每个请求携带自定义token 根据实际情况进行修改
            resolve(service(res.config))
          })
        })
      }
    } else if (code === 500) {
      Message({
        message: msg,
        type: 'error',
      })
      return Promise.reject(new Error(msg))
    } else if (code === 901) {
      Message({
        type: 'error',
        duration: 0,
        dangerouslyUseHTMLString: true,
        message: '<div>演示模式，无法进行操作</div>',
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      if (msg === '无效的刷新令牌') {
        console.log(msg)
      } else {
        Notification.error({
          title: msg,
        })
      }
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  (error) => {
    console.log('err' + error)
    let { message } = error
    if (message === 'NetWork Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

export function getBaseHeader() {
  return {
    Authorization: 'Bearer' + getAccessToken(),
  }
}

function handleAuthorized() {
  if (!isReLogin.show) {
    isReLogin.show = true
    MessageBox.confirm(
      '登录状态已过期，您可以继续留在该页面或重新登录页面',
      '系统提示',
      {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        isReLogin.show = false
        store.dispatch('LogOut').then(() => {
          location.href = getPath('/index')
        })
      })
      .catch(() => {
        isReLogin.show = false
      })
  }
  return Promise.reject('无效的会话，或会话已过期，请重新登录')
}
export default service
